<template>
  <div class="departments">
    <el-card class="card">
      <template #header>
        <div>组织结构</div>
      </template>
      <div class="other-content">
        <TreeItem :item="topInfo" :istop="true" />
        <hr>
        <!--
          el-tree
             data：数据
             props:{
               label:需要显示的文本字段
               children:对应子集字段
             }
             作用域插槽（重写每一项内容）  {node,data}
             node:elementui封装的一些内部数据
             data:当前点击项数据
         -->
        <el-tree :data="treeData" :props="{ label: 'name' }" default-expand-all>
          <template v-slot="{ data }">
            <TreeItem :item="data" style="width: 100%" @getData="getData" />
          </template>
        </el-tree>
      </div>
    </el-card>
    <Add :init-list="initList" @getData="getData" />
  </div>
</template>
<script>
import TreeItem from './components/TreeItem.vue'
import { companyDepartment } from '@/api/departments.js'
import Add from './components/Add.vue'
export default {
  components: {
    TreeItem,
    Add
  },
  data() {
    return {
      topInfo: {
        name: '传智教育',
        manager: '负责人',
        id: ''
      },
      treeData: [],
      initList: []
    }
  },
  async created() {
    this.getData()
  },
  methods: {
    // 获取组织架构数据
    async getData() {
      const res = await companyDepartment()
      this.initList = res.data.depts
      this.topInfo.name = res.data.companyName
      this.treeData = this.changeData(res.data.depts, '')
      console.log('组织架构数据', res)
    },
    // 树形数据转换
    changeData(arr, pid = '') {
      return arr.filter((item) => {
        if (item.pid === pid) {
          item.children = this.changeData(arr, item.id)
          return true
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.departments {
  padding: 15px;
  .card {
    padding: 15px;
    .other-content {
      padding: 0 30px;
    }
  }
}
</style>
